package org.mspring.mlog.api.spider.handler.impl;

import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mspring.mlog.api.spider.handler.ContentHandler;
import org.mspring.mlog.utils.UploadUtils;
import org.mspring.platform.utils.ImageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Gao Youbo
 * @since 2013-3-8
 */
public class ContentImageHandler implements ContentHandler {

    private static final Logger log = LoggerFactory.getLogger(ContentImageHandler.class);

    @Override
    public Element handle(Element content) {
        Map<String, String> img_urls = new HashMap<>();
        Elements imgs = content.select("img");
        for (Element img : imgs) {
            String src = img.attr("src");
            if (src.startsWith("/") || src.startsWith("\\") || !src.startsWith("http://") || !src.startsWith("https://")) {
                src = img.absUrl("src");
            }
            try {
                URL imgUrl = new URL(src);
                String new_src = img_urls.get(src);
                if (new_src == null) {
                    new_src = fetchImage(imgUrl);
                    img_urls.put(src, new_src);
                }
                img.attr("src", new_src);
            } catch (MalformedURLException e) {
                img.remove();
                log.error(e.getMessage(), e);
            }
        }
        return content;
    }

    public static String fetchImage(URL imgUrl) {
        try {
            HttpURLConnection httpConnection = (HttpURLConnection) imgUrl.openConnection();
            httpConnection.setRequestMethod("GET");
            BufferedInputStream bis = new BufferedInputStream(httpConnection.getInputStream());

            String ext = FilenameUtils.getExtension(imgUrl.toString());
            if (!ImageUtils.isImage(ext)) {
                ext = "jpg";
            }
            String filename = "/temp/" + UploadUtils.getUniqueFilename() + "." + ext;
            // String src = ServiceFactory.getStorageService().put(filename, bis);
            // return src;
            return null;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
